package com.zjitc.controller;

import com.zjitc.model.Car;
import com.zjitc.model.CarItem;
import com.zjitc.model.User;
import com.zjitc.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/5 0005
 * @description:
 */
@Controller
@RequestMapping(value = "/car")
public class CarControl {

    @Autowired
    private CarService carService;

    @RequestMapping(value = "/addCar")
    public ModelAndView addCar(String pid, int count, HttpSession session) {
        User user = (User) session.getAttribute("user");
        ModelAndView mv = new ModelAndView();
        if (user == null) {
            String msg = "请先登录";
            String address = "/jsp/login.jsp";

            mv.addObject("msg", msg);
            mv.addObject("address", address);
            mv.setView(new InternalResourceView("/jsp/msg.jsp"));
            return mv;
        } else {
            carService.add(user.getUid(), pid, count);
            return new ModelAndView("redirect:/car/findAll.do");
        }
    }

    @RequestMapping(value = "/findAll")
    public ModelAndView findAll(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<CarItem> items = carService.findAll(user.getUid());

        double total = 0.0;
        for (CarItem item : items) {
            total += item.getPrice();
        }
        ModelAndView mv = new ModelAndView(new InternalResourceView("/jsp/cart.jsp"));
        mv.addObject("car", items);
        mv.addObject("total", total);
        return mv;
    }

    @RequestMapping(value = "/clearCar")
    @ResponseBody
    public void clearCar(String uid) {
        carService.clear(uid);
    }

    @RequestMapping(value = "/deleteCarProductByPid")
    @ResponseBody
    public String deleteCarProductByPid(String pid, HttpSession session) {
        carService.delete(pid, session);
        return pid;
    }
}
